<template>
  <div>
    <!-- 查询栏 -->
    <el-form :inline="true" :model="baseWarehouseDTO" class="demo-form-inline">
      <el-form-item label="仓库编码">
        <el-input
          type="number"
          v-model="baseWarehouseDTO.warehouseId"
          placeholder="仓库编码"
          @keyup.enter.native="onSearch"
        ></el-input>
      </el-form-item>
      <el-form-item label="仓库名称">
        <el-input v-model="baseWarehouseDTO.warehouseName" placeholder="仓库名称" @keyup.enter.native="onSearch"></el-input>
      </el-form-item>
      <el-form-item label="仓库地址">
        <el-input v-model="baseWarehouseDTO.warehouseAddress" placeholder="仓库地址" @keyup.enter.native="onSearch"></el-input>
      </el-form-item>
      <el-form-item label="备注信息">
        <el-input v-model="baseWarehouseDTO.remarks" placeholder="备注信息" @keyup.enter.native="onSearch"></el-input>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="baseWarehouseDTO.status" placeholder="状态" clearable>
          <el-option label="正常" value="正常"></el-option>
          <el-option label="禁用" value="禁用"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch">查询</el-button>
        <el-button type="warning" @click="onReset">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 按钮 -->
    <el-button size="small" type="primary" @click="handleAdd" style="margin-left: 10px">新增</el-button>
    <el-button size="small" type="danger" @click="handleBatchDelete">删除</el-button>
    <el-button size="small" type="info" @click="handleImport">导入</el-button>
    <el-button size="small" type="warning" @click="handleExport">导出</el-button>
    <input type="file" ref="fileInput" @change="triggerImport" style="display: none;" accept=".xlsx, .xls" />
    <!-- 表格 -->
    <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="warehouseId" label="仓库编码"></el-table-column>
      <el-table-column prop="warehouseName" label="仓库名称"></el-table-column>
      <el-table-column label="仓库图片">
        <template slot-scope="scope">
          <image-preview :src="scope.row.image" />
        </template>
      </el-table-column>
      <el-table-column prop="warehouseAddress" label="仓库地址"></el-table-column>
      <el-table-column prop="remarks" label="备注信息"></el-table-column>
      <el-table-column prop="status" label="状态">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === '正常' ? 'success' : 'danger'">
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间"></el-table-column>
      <el-table-column prop="updateTime" label="更新时间"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="baseWarehouseDTO.pageNum"
      :page-sizes="[5,10,20]"
      :page-size="baseWarehouseDTO.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>

    <!-- 新增/修改弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="30%" @closed="resetForm('warehouseForm')">
      <el-form :model="form" :rules="rules" ref="warehouseForm">
        <el-form-item label="仓库名称" label-width="80px" prop="warehouseName">
          <el-input v-model="form.warehouseName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图片" label-width="80px" prop="image">
          <image-upload v-model="form.image" />
        </el-form-item>
        <el-form-item label="仓库地址" label-width="80px" prop="warehouseAddress">
          <el-input v-model="form.warehouseAddress" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="备注信息" label-width="80px" prop="remarks">
          <el-input v-model="form.remarks" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态" label-width="80px" prop="status">
          <el-select v-model="form.status" placeholder="状态" clearable>
            <el-option label="正常" value="正常"></el-option>
            <el-option label="禁用" value="禁用"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmDialog">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { find, add, update, deleteWarehouses, importBatch } from '@/api/base/warehouse'
import ImagePreview from '@/components/ImagePreview/index.vue'
import ImageUpload from '@/components/ImageUpload/index.vue'
export default {
  name: 'BaseWarehouse',
  components: { ImageUpload, ImagePreview },
  data() {
    return {
      baseWarehouseDTO: {
        warehouseId: '',
        warehouseName: '',
        warehouseAddress: '',
        remarks: '',
        status: '',
        pageNum: 1,
        pageSize: 5,
      },
      tableData: [],
      multipleSelection: [],
      total: 0,
      dialogVisible: false,
      dialogTitle: '',
      form: {
        warehouseName: '',
        image: '',
        warehouseAddress: '',
        remarks: '',
        status: ''
      },
      rules: {
        warehouseName: [
          { required: true, message: '请输入仓库名称', trigger: 'blur' }
        ],
        image: [
          { required: true, message: '请上传图片', trigger: 'change' }
        ],
        warehouseAddress: [
          { required: true, message: '请输入仓库地址', trigger: 'blur' }
        ],
        remarks: [
          { required: true, message: '请输入备注信息', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      },
    };
  },
  created() {
    this.fetchData();
  },
  methods: {
    // 查询仓库信息
    fetchData() {
      find(this.baseWarehouseDTO).then(res => {
        this.tableData = res.data.list;
        this.total = res.data.total;
        this.$message({
          message: '查询成功!',
          type: 'success',
          duration: 1200
        });
      });
    },
    // 触发导入文件选择
    handleImport() {
      this.$refs.fileInput.click();
    },
    // 处理文件选择并上传
    triggerImport(e) {
      const file = e.target.files[0];
      if (file) {
        this.importData(file);
      }
    },
    // 导入
    importData(file) {
      importBatch(file).then(() => {
        this.$message({
          message: '导入成功!',
          type: 'success',
          duration: 1200
        });
        this.baseWarehouseDTO.pageNum = 1;
        this.fetchData();
      });
    },
    // 导出
    handleExport() {
      window.location.href = 'http://localhost:8888/base/warehouse/export';
    },
    // 重置表单
    resetForm(formName) {
      this.dialogVisible = false;
      this.$refs[formName].resetFields();
      this.form = {
        warehouseName: '',
        image: '',
        warehouseAddress: '',
        remarks: '',
        status: ''
      };
    },
    // 条件查询
    onSearch() {
      this.baseWarehouseDTO.pageNum = 1;
      this.fetchData();
    },
    // 重置查询条件
    onReset() {
      this.baseWarehouseDTO.warehouseId = '';
      this.baseWarehouseDTO.warehouseName = '';
      this.baseWarehouseDTO.warehouseAddress = '';
      this.baseWarehouseDTO.remarks = '';
      this.baseWarehouseDTO.status = '';
      this.fetchData();
    },
    // 多选
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 修改按钮
    handleEdit(index, row) {
      this.dialogTitle = '修改仓库';
      this.form = { ...row };
      this.dialogVisible = true;
    },
    // 新增按钮
    handleAdd() {
      this.dialogTitle = '新增仓库';
      this.dialogVisible = true;
    },
    // 单选删除
    handleDelete(index, row) {
      const warehouseName = row.warehouseName;
      this.$confirm(`确定要删除仓库 "${warehouseName}" 吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteWarehouses(row.warehouseId).then(response => {
          this.$message({
            message: '删除成功!',
            type: 'success',
            duration: 1200
          });
          this.fetchData();
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 批量删除
    handleBatchDelete() {
      if (this.multipleSelection.length === 0) {
        this.$message({
          message: '请选择要删除的数据!',
          type: 'warning',
          duration: 1200
        });
        return;
      } else {
        const warehouseNames = this.multipleSelection.map(item => item.warehouseName).join(', ');
        this.$confirm(`确定要删除以下仓库吗？\n${warehouseNames}`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const ids = this.multipleSelection.map(item => item.warehouseId).join(',');
          deleteWarehouses(ids).then(response => {
            this.$message({
              message: '删除成功!',
              type: 'success',
              duration: 1200
            });
            this.fetchData();
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      }
    },
    // 提交新增/修改
    confirmDialog() {this.$refs.warehouseForm.validate(valid => {
      if (valid) {
        if (this.dialogTitle === '新增仓库') {
          add(this.form).then(response => {
            this.$message({
              message: '新增成功!',
              type: 'success',
              duration: 1200
            });
            this.fetchData();
            this.dialogVisible = false;
          });
        } else {
          update(this.form).then(response => {
            this.$message({
              message: '修改成功!',
              type: 'success',
              duration: 1200
            });
            this.fetchData();
            this.dialogVisible = false;
          });
        }
      } else {
        this.$message({
          message: '表单验证失败!',
          type: 'error',
          duration: 1200
        });
        return false;
      }
    });
    },
    // 改变每页大小
    handleSizeChange(val) {
      this.baseWarehouseDTO.pageSize = val;
      this.fetchData();
    },
    // 改变当前页码
    handleCurrentChange(val) {
      this.baseWarehouseDTO.pageNum = val;
      this.fetchData();
    },
  }
};
</script>

<style scoped lang="scss">
.demo-form-inline {
  margin-left: 10px;
  margin-top: 10px;
}
.el-pagination {
  margin: 5px;
  text-align: center;
}
</style>
